package org.oschina.api.friendlink.service;

import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.friendlink.dao.FriendlinkDAO;
import org.oschina.api.friendlink.model.Friendlink;
import org.oschina.api.friendlink.vo.FriendlinkVo;
import org.oschina.bean.Result;
import org.oschina.security.ISecurity;
import org.oschina.security.annotation.Require;
import org.oschina.api.index.service.IndexService;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FriendlinkService extends BaseService {

	@Autowired
	private FriendlinkDAO friendlinkDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private ISecurity security;
	
	/**
	 * 返回
	 * @return
	 */
	public List<FriendlinkVo> findVo()
	{
		List<FriendlinkVo> result=_findVo();
		if(!security.require(new String[]{Module.MODULE_21}, getToken(), false))
		{
			for(FriendlinkVo friendlinkVo:result)
			{
				friendlinkVo.setId(null);
				friendlinkVo.setIndex(null);
				friendlinkVo.setCreate_time(null);
			}
		}
		return result;
	}
	
	/**
	 * 创建
	 * @param friendlink
	 * @return
	 */
	@Require(authorization=Module.MODULE_21)
	public Result create(Friendlink friendlink)
	{
		return ResultUtil.getSuccess(_create(friendlink));
	}
	
	/**
	 * 更新
	 * @param friendlink
	 * @return
	 */
	@Require(authorization=Module.MODULE_21)
	public Result update(Friendlink friendlink)
	{
		if(_update(friendlink)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(friendlink);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@Require(authorization=Module.MODULE_21)
	public Result remove(int id)
	{
		if(_remove(id)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(Message.DELETE_SUCCESS);
	}
	
	/**
	 * 返回
	 * @return
	 */
	private List<FriendlinkVo> _findVo()
	{
		return friendlinkDAO.findVo();
	}
	
	/**
	 * 创建
	 * @param friendLink
	 * @return
	 */
	private Friendlink _create(Friendlink friendLink)
	{
		friendLink.setId(_getIndex());
		friendLink.setCreate_time(DateUtil.now());
		return friendlinkDAO.create(friendLink);
	}
	
	/**
	 * 更新
	 * @param friendLink
	 * @return
	 */
	private int _update(Friendlink friendLink)
	{
		return friendlinkDAO.update(friendLink);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	private int _remove(int id)
	{
		return friendlinkDAO.remove(id);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_FRIENDLINK);
	}
}